package com.xxyf.service;

import com.xxyf.mapper.UsernotoMapper;
import com.xxyf.pojo.Usernoto;
import com.xxyf.tools.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @Author 小小怡飞
 * @Date 2022/9/4 15:37
 * @Version JDK 8
 */
@Service
@Slf4j
public class NoteServiceimp implements NoteService{

    @Autowired
    UsernotoMapper usernoto;
    @Resource
    RedisTemplate<String,Object> redisTemplate;

    @Override
    public Rest count(Integer uid,String grouo) {
        if (grouo!=null && grouo.equals("")){
            grouo=null;
        }
        String count1 = Scope.getScope(Scope.NOTE, "count", uid, grouo);
        Integer rest = (Integer) redisTemplate.opsForValue().get(count1);
        if (rest!=null){
            redisTemplate.expire(count1,60*30, TimeUnit.SECONDS);
            Page page=new Page(rest, NumerUtils.size, 1);
            return new Rest(page);
        }
        Rest code =new Rest(Code.erro, "请求错误");
        if (NumerUtils.isnotnull(uid)){
            Integer count = usernoto.count(uid, grouo);
            Page page=new Page(count, NumerUtils.size, 1);
            code = new Rest(page);
            redisTemplate.opsForValue().set(count1,count,60*30, TimeUnit.SECONDS);
            return code;
        }

        return code;
    }

    @Override
    public Rest pageNote(Integer uid, String grouo, Integer total, Integer number) {
//        统一替换
        if (grouo!=null && grouo.equals("")){
            grouo=null;
        }
//        redis zset 键
        String note
                = Scope.getScope(Scope.NOTE, "pageNote", uid, grouo);

//       分页类
        Page page=null;

        Rest restpage = new Rest(Code.erro, "请求错误!");
        if (!NumerUtils.isnotnull(uid)){
            return restpage;
        }
        if (!NumerUtils.isnotnull(total)){
            return new Rest(Code.erro,"暂无数据无数据");
        }
        if (!NumerUtils.isnotnull(number)){
            return restpage;
        }

//        if (StringUtils.hasText(grouo)){
//            Page data = (Page) count(uid, number,grouo).getData();
//            Integer count = data.getTotal();
//            if (NumerUtils.isnotnull(count)){
//                page = new Page(count, NumerUtils.size, number);
//            }else {
//                return new Rest(Code.erro,"未找到分组");
//            }
//        }else {
        page = new Page(total, NumerUtils.size, number);
//      初始化类 获取 页数 与索引



//        }
//      数据是否正常
        if (page.isSucceed()){
            if (number<=4){
                Set<Object> range = redisTemplate.opsForZSet().range(note, page.getStart(), page.getEnd() - 1);
                log.debug(String.valueOf(page.getStart()));
                log.debug(String.valueOf(page.getEnd() - 1));

                if (range!=null && range.size()!=0){
//                    if (total>=NumerUtils.size*4){
//                        if (NumerUtils.size*4==range.size()){
//                            redisTemplate.expire(note,30*60,TimeUnit.SECONDS);
//                            return new Rest(range);
//                        }
//                    }else {
//                        if (total==range.size()){
                            redisTemplate.expire(note,30*60,TimeUnit.SECONDS);
                            return new Rest(range);
//                        }
//                    }

                }
                List<Usernoto> pageNote = usernoto.pageNote(uid, grouo, 0, NumerUtils.size*4);

                for (int i = 0 ; i<pageNote.size();i++){
                    redisTemplate.opsForZSet().add(note,pageNote.get(i),i);
                }
                redisTemplate.expire(note,30*60,TimeUnit.SECONDS);
                log.debug("走查询");
                return new Rest(pageNote.subList(page.getStart(),page.getEnd()));
            }
            note= note+":"+number;
            Set<Object> range = redisTemplate.opsForZSet().range(note, 0, 4);
            if (range!=null && range.size()!=0){
                redisTemplate.expire(note,30*60,TimeUnit.SECONDS);
                return new Rest(range);
            }

//            查询数据库
            List<Usernoto> pageNote = usernoto.pageNote(uid, grouo, page.getStart(), page.getSize());
            restpage = new Rest(pageNote);
            for (int i = 0 ; i<pageNote.size();i++){
                redisTemplate.opsForZSet().add(note,pageNote.get(i),i);
            }

            redisTemplate.expire(note,30*60,TimeUnit.SECONDS);

            return restpage;
        }
        return restpage;
    }

    @Override
    @Transactional
    public Rest onedelect(Usernoto noto) {

        if (noto !=null &&!NumerUtils.isnotnull(noto.getUserid())){
            return new Rest(Code.erro,"请求错误");
        }
        Integer id = noto.getId().intValue();
        Integer uid = noto.getUserid();
        int onedelete = usernoto.onedelete(id);
        if (onedelete>0){
            String pageNote = Scope.getScope(Scope.NOTE, "pageNote",uid,noto.getGrouo());
            String pageNote1 = Scope.getScope(Scope.NOTE, "pageNote",uid,null);

            String count = Scope.getScope(Scope.NOTE, "count",uid,noto.getGrouo());
            String count1= Scope.getScope(Scope.NOTE, "count",uid,null);

            Long remove = redisTemplate.opsForZSet().remove(pageNote, 1, noto);
            if (remove!=null && remove==1){
                redisTemplate.opsForValue().increment(count,-1);
            }
            Long remove1 = redisTemplate.opsForZSet().remove(pageNote1, 1, noto);
            if (remove1!=null && remove1==1){
                redisTemplate.opsForValue().increment(count1,-1);
            }
            if (remove1!=null && remove1==1 || remove!=null && remove==1){
                String page = Scope.getScope(Scope.NOTE, "pageNote",noto.getUserid(),noto.getGrouo(),"*");
                String page1 = Scope.getScope(Scope.NOTE, "pageNote",noto.getUserid(),null,"*");
                Set<String> keys = redisTemplate.keys(page1);
                Set<String> keys1 = redisTemplate.keys(page);
                
                redisTemplate.delete(keys);
                redisTemplate.delete(keys1);
            }

            return new Rest(Code.succeed,"删除成功");
        }
        return new Rest(Code.erro,"删除失败");
    }

    @Override
    public Rest reg(Usernoto noto) {

        if (noto!=null){

            Timestamp gtmModifide = noto.getGtmModifide();
            Usernoto noto1 = this.usernoto.idquery(noto.getId());
            int reg = 0;
            try {
                reg = this.usernoto.reg(noto);
            } catch (DataAccessException e) {
                e.printStackTrace();
                return new Rest(Code.erro,"参数错误");
            }
            noto.setVersion(noto.getVersion()+1);
            String pageNote = Scope.getScope(Scope.NOTE, "pageNote",noto.getUserid(),noto.getGrouo());
            String pageNote1 = Scope.getScope(Scope.NOTE, "pageNote",noto.getUserid(),null);

            Long remove = redisTemplate.opsForZSet().remove(pageNote, 1, noto1);

            Long remove1 = redisTemplate.opsForZSet().remove(pageNote1, 1, noto1);

            if (remove!=null && remove==1){
                redisTemplate.opsForZSet().add(pageNote,noto,0);
            }
            if (remove1!=null && remove1==1){
                redisTemplate.opsForZSet().add(pageNote1,noto,0);
            }
            if (remove1!=null && remove1==1 || remove!=null && remove==1){
                String page = Scope.getScope(Scope.NOTE, "pageNote",noto.getUserid(),noto.getGrouo(),"*");
                String page1 = Scope.getScope(Scope.NOTE, "pageNote",noto.getUserid(),null,"*");
                Set<String> keys = redisTemplate.keys(page1);
                Set<String> keys1 = redisTemplate.keys(page);

                redisTemplate.delete(keys);
                redisTemplate.delete(keys1);
            }

            return new Rest(Code.succeed,"修改成功");

        }
        return new Rest(Code.erro,"请求异常!");
    }

    @Override
    @Transactional
    public Rest noteput(Usernoto noto) {
        if (noto!=null){
            long date = System.currentTimeMillis();
            Integer reg = null;
            noto.setGtmCreate(new Timestamp(date));
            noto.setGtmModifide(new Timestamp(date));
            Integer uid = noto.getUserid();
            try {
                reg = usernoto.noteput(noto);

            } catch (DataAccessException e) {
                e.printStackTrace();
                return new Rest(Code.erro,"参数错误");
            }


            noto.setDeleted(0);
            if (reg>0){
                Usernoto user = null;
                try {
                    System.out.println(noto);
                    user = usernoto.oneNote(noto);
                    String count = Scope.getScope(Scope.NOTE, "count",uid,noto.getGrouo());
                    String count1= Scope.getScope(Scope.NOTE, "count",uid,null);

                    redisTemplate.opsForValue().increment(count,1);
                    redisTemplate.opsForValue().increment(count1,1);

                    String pageNote = Scope.getScope(Scope.NOTE, "pageNote",noto.getUserid(),noto.getGrouo());
                    String pageNote1 = Scope.getScope(Scope.NOTE, "pageNote",noto.getUserid(),null);

                    redisTemplate.opsForZSet().add(pageNote,user,0);
                    redisTemplate.opsForZSet().add(pageNote1,user,0);

                    String page = Scope.getScope(Scope.NOTE, "pageNote",noto.getUserid(),noto.getGrouo(),"*");
                    String page1 = Scope.getScope(Scope.NOTE, "pageNote",noto.getUserid(),null,"*");
                    Set<String> keys = redisTemplate.keys(page1);
                    Set<String> keys1 = redisTemplate.keys(page);

                    redisTemplate.delete(keys);
                    redisTemplate.delete(keys1);

                } catch (DataAccessException e) {
                    new Rest(Code.erro,"重复单词!");
                    e.printStackTrace();
                }
                return new Rest(Code.succeed,user,"请求成功");
            }
            return new Rest(Code.erro,"请求异常!");
        }
        return new Rest(Code.erro,  "没有数据请重试!");
    }
}
